//
//  RHWelcomeView.swift
//  微博新浪
//
//  Created by hezerong on 16/6/10.
//  Copyright © 2016年 Rocky. All rights reserved.
/*
  UIView的生命周期函数
1, didMoveToSuperView -> didMoveToWindow -> layoutSubViews
2, layoutSubView之后，自动布局才会生效，layoutSubViews可能会多次调用，比如说添加子view
3, 调用layoutIfNeeded,可以强制调用，layoutsubviews， 更新UI

*/

import UIKit
import SDWebImage

class RHWelcomeView: UIView {
    

    
    //头像
    lazy var vartar_large:UIImageView = UIImageView()
    
    //欢迎文字
    lazy var welcomeLable: UILabel = UILabel(text: "\(UserAccount.sharedUserAccunt.screen_name!)欢迎回来", fontSize: 16)
    


    init(){
        
    
    super.init(frame:  screenBounds)
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func didMoveToWindow() {
        
//        addAnimation()
        addSpringAnimation()

        
        super.didMoveToWindow()

        
    }

}

extension RHWelcomeView{

    func setUpUI(){
    
      self.backgroundColor = UIColor(patternImage: UIImage(named: "ad_background")!)
        
        
      //添加子控件
        self.addSubview(vartar_large)
        self.addSubview(welcomeLable)
        
     //自动布局
        vartar_large.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).offset(-50)
            make.size.equalTo(CGSizeMake(90, 90))
        }
        
        welcomeLable.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).offset(50)
            
        }
        
        //设置头像图片
      vartar_large.sd_setImageWithURL(NSURL(string: UserAccount.sharedUserAccunt.avatar_large!), placeholderImage: UIImage(named:"avatar_default_big"))
        



        
        //裁剪圆形头像
        vartar_large.layer.cornerRadius = 45
        vartar_large.layer.masksToBounds = true
        
        self.layoutIfNeeded()
    }
}

extension RHWelcomeView{

    func addAnimation(){
    
       let animationSpinning = CABasicAnimation( keyPath: "transform.rotation")
        
        animationSpinning.duration = 5
        animationSpinning.toValue = M_PI * 2
        animationSpinning.repeatCount = MAXFLOAT
        self.vartar_large.layer.addAnimation(animationSpinning, forKey: nil)
    }
    
    
    
    //弹力动画
    func addSpringAnimation(){
    
        vartar_large.snp_updateConstraints { (make) -> Void in
        
        make.centerY.equalTo(self).offset(-100)
        }
        
         UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 20, options: [], animations: { () -> Void in
            
            self.layoutIfNeeded()
            
            }) { (finish) -> Void in
                
                self.removeFromSuperview()
        }
    }
}





